package com.example.message2;
import java.util.ArrayList;
import java.util.Calendar;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MessageDataSource {
			/*
		 * Private members
		 */
	
		private SQLiteDatabase db;
		private MessageSQLiteHelper dbHelper;
		private String[] allColumns = { 
			MessageSQLiteHelper.COLUMN_ID,
			MessageSQLiteHelper.COLUMN_LAST_READ
				};
		
		private String[] allMessages = {
			MessageSQLiteHelper.COLUMN_MESSAGE_ID,
			MessageSQLiteHelper.COLUMN_MESSAGE_SENDER,
			MessageSQLiteHelper.COLUMN_MESSAGE_RECEIVER,
			MessageSQLiteHelper.COLUMN_MESSAGE_TEXT
		};
		
		
		//Constructor
		 
	
		public MessageDataSource(Context context){
			dbHelper = new MessageSQLiteHelper(context);
		}
		
		//DB operations
		 
		public void open() throws SQLException{
			db = dbHelper.getWritableDatabase();
		}
		
		public void close(){
			dbHelper.close();
		}
		
		// Common queries
		 
		
		//Returns all contacts
		private Cursor queryAll(){
			Cursor cursor = db.query(MessageSQLiteHelper.TABLE_USERS, allColumns, null, null, null, null, null);
			return cursor;
		}
		
		//Returns all groups ???
		
		private Cursor queryAllMessages(int id){
			Cursor cursor2 = db.query(MessageSQLiteHelper.TABLE_MESSAGES, allMessages, MessageSQLiteHelper.COLUMN_MESSAGE_RECEIVER + " = " + id, null, null, null, null, null);
			return cursor2;
		}
		

		//Add, update, delete operations
		 
		public User addContact(User u){
			addUser(u.getId(),u.getLastRead());
			return u;
		}

		public User addUser(int id,int lastRead){
			
			//Prepare INSERT query, add column names and values
			ContentValues values = new ContentValues();
			values.put(MessageSQLiteHelper.COLUMN_ID,id);
			values.put(MessageSQLiteHelper.COLUMN_LAST_READ,lastRead);
			//INSERT into contacts table
			long insertId = db.insert(MessageSQLiteHelper.TABLE_USERS, null, values);
			
			//Get a cursor pointing to the newly created contact
			Cursor cursor = db.query(MessageSQLiteHelper.TABLE_USERS, allColumns, MessageSQLiteHelper.COLUMN_ID + " = " + insertId, null, null, null, null);
			cursor.moveToFirst();
			
			User newUser = cursorToUser(cursor);
			
			cursor.close();
			
			return newUser;
		}
		/*
		//Update contact 
		public Contact updateContact(Contact contact) throws Exception{
			String NAME_UPDATE = "UPDATE contacts SET name= " + "'" + contact.getName() + "'" + " WHERE _id = " + contact.getId();
			String ADDRESS_UPDATE = "UPDATE contacts SET address= " + "'" + contact.getAddress() + "'" + " WHERE _id = " + contact.getId();
			String CELL_UPDATE = "UPDATE contacts SET cell= " + "'" + contact.getCell() + "'" + " WHERE _id = " + contact.getId();
			String ALT_UPDATE = "UPDATE contacts SET alt= " + "'" + contact.getAlt() + "'" + " WHERE _id = " + contact.getId();
			String EMAIL_UPDATE = "UPDATE contacts SET email= " + "'" + contact.getEmail() + "'" + " WHERE _id = " + contact.getId();
			String COMMENTS_UPDATE = "UPDATE contacts SET comments= " + "'" + contact.getComments() + "'" + " WHERE _id = " + contact.getId();
			String GROUP_UPDATE = "UPDATE contacts SET groupsid= " + "'" + contact.getGroup() + "'" + " WHERE _id = " + contact.getId();
			
			db.execSQL(NAME_UPDATE);
			db.execSQL(ADDRESS_UPDATE);
			db.execSQL(CELL_UPDATE);
			db.execSQL(ALT_UPDATE);
			db.execSQL(EMAIL_UPDATE);
			db.execSQL(COMMENTS_UPDATE);
			db.execSQL(GROUP_UPDATE);

			return contact;
		}*/
		
		public void deleteMessage(int messageID) throws Exception{
			db.execSQL("DELETE FROM messages WHERE _id = '" + messageID + "'");
		}
		
		/*public void testContact(){
			String DATABASE_TESTDATA = "INSERT INTO contacts (name, address, cell, alt, email, comments, cat1, cat2, cat3, cat4, cat5) VALUES (" + 
					"\"Chris Williams\",\"123 E. Marquette St. Appleton, WI\",\"9202686853\",\"9209547244\", " + 
					"\"willic82@uwosh.edu\",\"SE Major\", 0, 0, 0, 0, 0)"; 
			db.execSQL(DATABASE_TESTDATA);
		}*/
		
		//Get methods
		 
		public ArrayList<User> getAllContacts(){	
			Cursor cursor = queryAll();
			ArrayList<User> contacts = cursorToUserList(cursor);
			cursor.close();
			return contacts;
		}
		
		public User getUserById(int id){
			Cursor c = db.query(MessageSQLiteHelper.TABLE_USERS, allColumns, MessageSQLiteHelper.COLUMN_ID + " = " + id, null, null, null, null);
			if(c.getCount() == 0){
				Log.d("CM", "Couldn't find contact with id " + id);
				return null;
			}
			c.moveToFirst();
			return cursorToUser(c);
		}
		
		public ArrayList<Message> getMessage(int messageID){
			String table1=MessageSQLiteHelper.TABLE_MESSAGES;
			//String table2=MessageSQLiteHelper.TABLE_GROUPS;
			//String groupIDColumn= MessageSQLiteHelper.COLUMN_GROUP_ID;
			String contactGroupID = MessageSQLiteHelper.COLUMN_MESSAGE_ID;
			//String MY_QUERY = "SELECT * FROM "+table1+ "AS a, "+table2+" AS b INNER JOIN a."+contactGroupID+" ON b."+groupIDColumn+" WHERE a."+contactGroupID+" AND b."+groupIDColumn+"=?";
			ArrayList<Message> message;
			Cursor cursor;
			if(messageID!=1){
				String MY_QUERY = "SELECT * FROM "+table1+ " WHERE "+contactGroupID+" = ?";
				cursor = db.rawQuery(MY_QUERY,new String[]{""+messageID});
				message = cursorToMessageList(cursor);
			}
			else{
				cursor = db.query(MessageSQLiteHelper.TABLE_USERS, allColumns, null, null, null, null, null);
				message = cursorToMessageList(cursor);
			}
			//Cursor cursor = db.queryMessageSQLiteHelper.TABLE_CONTACTS, allColumns, null, null, null, null, null);
			

			cursor.close();
			return message;
		}
		
		public ArrayList<Message> getMessagesById(int id){	
			Cursor cursor = queryAllMessages(id);
			ArrayList<Message> messages = cursorToMessageList(cursor);
			for(Message m : messages){
				Log.d("CM", "ID: " + m.getId());
			}
			cursor.close();
			return messages;
		}	
		
		//Conversion methods
		 
		private User cursorToUser(Cursor cursor){
			User user = new User();
			user.setId(cursor.getInt(0));
			user.setLastRead(cursor.getInt(1));
			return user;
		}
		
		private Message cursorToMessage(Cursor cursor){
			Message message = new Message();
			message.setId(cursor.getInt(0));
			message.setSender(cursor.getInt(1));
			message.setReceiver(cursor.getInt(3));
			message.setText(cursor.getString(4));

			return message;
		}
		
		private ArrayList<User> cursorToUserList(Cursor cursor){
			ArrayList<User> list = new ArrayList<User>();
			cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		      User user = cursorToUser(cursor);
		      list.add(user);
		      cursor.moveToNext();
		    }
		    return list;
		}
		
		private ArrayList<Message> cursorToMessageList(Cursor cursor){
			ArrayList<Message> list = new ArrayList<Message>();
			cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		      Message message = cursorToMessage(cursor);
		      list.add(message);
		      cursor.moveToNext();
		    }
		    return list;
		}
}